package com.think.cloud.thinkshop.auth.service;

import com.think.cloud.thinkshop.auth.form.LoginDTO;
import com.think.cloud.thinkshop.system.api.RemoteMallService;
import com.think.cloud.thinkshop.system.api.dto.AuthUserDTO;
import com.think.cloud.thinkshop.system.api.dto.MemberUserDTO;
import com.think.common.core.constant.Constants;
import com.think.common.core.domain.R;
import com.think.common.core.enums.UserType;
import com.think.common.core.exception.util.ServiceExceptionUtil;
import com.think.common.core.model.LoginUser;
import com.think.common.core.utils.StringUtils;
import com.think.common.core.utils.bean.BeanUtils;
import com.think.common.security.service.LoginVO;
import com.think.common.security.service.TokenService;
import com.think.common.security.utils.SecurityUtils;
import me.zhyd.oauth.model.AuthUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.think.common.core.exception.enums.ErrorCode.*;

/**
 * @author zkthink
 * @apiNote
 **/
@Service
public class AppAuthService {
    private final Logger log = LoggerFactory.getLogger(AppAuthService.class);
    @Autowired
    private RemoteMallService remoteMallService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysRecordLogService recordLogService;

    public LoginVO login(LoginDTO loginDTO) {
        R<MemberUserDTO> r = remoteMallService.getByUsername(loginDTO.getEmail());
        if(R.isError(r)){
            throw ServiceExceptionUtil.exception(SYSTEM_BUSY);
        }
        MemberUserDTO data = r.getData();
        if(StringUtils.isNull(data)){
            throw ServiceExceptionUtil.exception(USER_NOT_EXIST);
        }
        if(!matches(data.getPassword(),loginDTO.getPassword())){
            throw ServiceExceptionUtil.exception(USERNAME_OR_PASSWORD_ERROR);
        }
        //生成token
        LoginUser loginUser = new LoginUser();
        Long userId = data.getId();
        loginUser.setUserid(userId);
        loginUser.setUsername(data.getUsername());
        loginUser.setUserType(UserType.CLIENT_USER.getDescription());
        recordLogService.recordLogininfor(userId,data.getUsername(), Constants.LOGIN_SUCCESS, "登录成功");
        remoteMallService.runMemberGroupUserUpdateByUserId(userId);
        return tokenService.createToken(loginUser);
    }

    public LoginVO callback(AuthUser authUser) {
        AuthUserDTO authUserDTO = new AuthUserDTO();
        BeanUtils.copyProperties(authUser,authUserDTO);
        R<MemberUserDTO> r = remoteMallService.oauthCallback(authUserDTO);
        log.info("授权回调: authUserDTO:{},callback:{}",authUserDTO,r);
        if(R.isError(r)){
            throw ServiceExceptionUtil.exception(SYSTEM_BUSY);
        }
        MemberUserDTO data = r.getData();
        //生成token
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(data.getId());
        loginUser.setUsername(data.getUsername());
        loginUser.setUserType(UserType.CLIENT_USER.getDescription());
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验密码是否正确
     * @param encodedPassword 数据库密码
     * @param password 用户输入密码
     * @return /
     */
    public boolean matches(String encodedPassword, String password)
    {
        return SecurityUtils.matchesPassword(password, encodedPassword);
    }
}
